package com.aisb.core.log;

import com.aisb.core.InitParam;
import com.aisb.core.SessionBean;
import com.aisb.core.util.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Description：
 * @Author wucm
 * @Date 2018/1/6
 */
@Aspect
@Component
public class LogVisitAspect {
    private  static  final Logger logger = LoggerFactory.getLogger(LogVisitAspect. class);

    @Autowired
    LogDao logDao;

    @Pointcut("@annotation(com.aisb.core.log.LogVisit)")
    public  void logVisitPointCut() {
    }

    @After("logVisitPointCut()")
    public void doAfter(JoinPoint joinPoint){
        MethodSignature sign =  (MethodSignature)joinPoint.getSignature();
        Method method = sign.getMethod();
        LogVisit annotation = method.getAnnotation(LogVisit.class);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();
        if(null == sessionBean){
            return;
        }

        LogVisitBean log = new LogVisitBean();
        log.setLogContent("访问"+annotation.value());
        log.setUserId(sessionBean.getUserId());
        log.setUserName(sessionBean.getUserName());
        log.setLogId(sessionBean.getLogId());
        log.setLogTime(DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

        logDao.insertVisitLog(log);
    }
}
